package com.framework.shs.commom.security.shiro;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.framework.shs.a.entity.User;
import com.framework.shs.a.service.UserService;

public class ShiroDbRealm extends AuthorizingRealm {
	// 继承AuthorizingRealm类，且重写doGetAuthorizationInfo及doGetAuthenticationInfo方法
	// doGetAuthorizationInfo ： 验证当前Subject（可理解为当前用户）所拥有的权限，且给其授权。在下一章说明。
	// doGetAuthenticationInfo ： 验证当前Subject登录。

	@Autowired
	private UserService userService;
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {

//		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//		authorizationInfo.setRoles(userService.findRoles(username));
//		authorizationInfo.setStringPermissions(userService.findPermissions(username));
		return authorizationInfo;
	}

	/**
	 * 认证回调函数,登录时调用.
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		// UsernamePasswordToken对象用来存放提交的登录信息
		// 可进行加密
		/*
		 * Subject subject=SecurityUtils.getSubject();
		 * if(subject.isAuthenticated()){ //登出 subject.logout(); }
		 */
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String username = token.getUsername();
		String password = new String(token.getPassword());
		User user = new User();
		user.setName(username);
		// 查出是否有此用户
		user = userService.findByName(token.getUsername());
		if (user != null) {
			if (user.getPassword().equals(password)) {
				// 若存在，将此用户存放到登录认证info中
				user.setUpdateBy(user.getId());
				user.setUpdateDate(new Date());
				HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();   
				user.setOldLoginIp(request.getRemoteAddr());
				userService.updateUser(user);
				return new SimpleAuthenticationInfo(user.getId(), password,getName());
			}
		}
		throw new UnauthenticatedException();
	}
}
